package com.party.course.service.impl;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.business.domain.Kc;
import com.party.business.domain.TOrder;
import com.party.business.mapper.KcMapper;
import com.party.business.mapper.TOrderMapper;
import com.party.common.core.domain.entity.SysUser;
import com.party.course.domain.BearInfo;
import com.party.course.domain.PayGroup;
import com.party.course.domain.StudentInfo;
import com.party.course.mapper.BearInfoMapper;
import com.party.course.mapper.PayGroupMapper;
import com.party.course.mapper.StudentInfoMapper;
import com.party.course.util.DateTimeUtill;
import com.party.course.util.SendQWmsgUtil;
import com.party.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.party.course.mapper.DispatchInfoMapper;
import com.party.course.domain.DispatchInfo;
import com.party.course.service.IDispatchInfoService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.party.common.utils.SecurityUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static net.sf.jsqlparser.util.validation.metadata.NamedObject.user;

/**
 * 派单记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class DispatchInfoServiceImpl extends ServiceImpl<DispatchInfoMapper, DispatchInfo> implements IDispatchInfoService {
    @Resource
    private DispatchInfoMapper dispatchInfoMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private PayGroupMapper payGroupMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;

    /**
     * 查询派单记录
     *
     * @param id 派单记录主键
     * @return 派单记录
     */
    @Override
    public DispatchInfo view(String id) {
        return dispatchInfoMapper.selectDispatchInfoById(id);
    }

    /**
     * 查询派单记录列表
     *
     * @param dispatchInfo 派单记录
     * @return 派单记录
     */
    @Override
    public List<DispatchInfo> findList(DispatchInfo dispatchInfo) {
        return dispatchInfoMapper.selectDispatchInfoList(dispatchInfo);
    }


    @Resource
    private KcMapper kcMapper;

    @Resource
    private BearInfoMapper bearInfoMapper;
    @Resource
    private TOrderMapper tOrderMapper;

    /**
     * 新增派单记录
     *
     * @param dispatchInfo 派单记录
     * @return 结果
     */
    @Override
    @Transactional
    public int add(DispatchInfo dispatchInfo) {
        // 检查承担量是否足够
        if (StrUtil.isNotEmpty(dispatchInfo.getPayGroupId())) {
            PayGroup payGroup = payGroupMapper.selectPayGroupById(dispatchInfo.getPayGroupId());
            if (ObjectUtil.isNotEmpty(payGroup)) {

                TOrder byOrderNo = tOrderMapper.findByOrderNo(dispatchInfo.getOrderCode());
                Kc kc = kcMapper.selectKcById(dispatchInfo.getClassId());
                String isTest = kc.getIsTy();

                String expectTime = byOrderNo.getQwskDate();
                //处理期望上课的时间格式
                String[] parts = expectTime.split(" ");
                String date = parts[0];
                String timePart = parts[1];
                // 转换日期为星期几
                String weekDay = DateTimeUtill.getWeek(date);
                String paramTime = timePart;
                String createBy = payGroup.getCreateBy();
                BearInfo bearInfo = null;
                if ("1".equals(isTest)) {
                    bearInfo = bearInfoMapper.findUseByUserIdTest(createBy.toString(),weekDay, paramTime);
                } else {
                    bearInfo = bearInfoMapper.findUseByUserId(createBy.toString(), weekDay,paramTime);
                }
                if (bearInfo==null) {
                    throw new RuntimeException("该交付小组承担量不足，无法派单");
                }
            }
        }
        dispatchInfo.setId(IdUtil.simpleUUID());
        dispatchInfo.setDelFlag("0");
        if (StrUtil.isEmpty(dispatchInfo.getDisTime())) {
            dispatchInfo.setDisTime(DateUtil.now());
        }
        if (StrUtil.isNotEmpty(dispatchInfo.getCenterId())) {
            SysUser user = sysUserMapper.selectUserById(Long.parseLong(dispatchInfo.getCenterId()));
            dispatchInfo.setCenterName(user.getUserName());
        }
        if (StrUtil.isEmpty(dispatchInfo.getStudentId())) {
            throw new RuntimeException("学生信息不能为空");
        }
        StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(dispatchInfo.getStudentId());
        if (ObjectUtil.isNotEmpty(studentInfo)) {
            studentInfo.setPayGroupId(dispatchInfo.getPayGroupId());
            studentInfo.setDispatchTime(dispatchInfo.getDisTime());
            studentInfo.setDispatchRemark(dispatchInfo.getRemark());
            studentInfoMapper.updateById(studentInfo);

        }
        if (StrUtil.isNotEmpty(dispatchInfo.getPayGroupId())) {
            PayGroup payGroup = payGroupMapper.selectPayGroupById(dispatchInfo.getPayGroupId());
            dispatchInfo.setPayGroupName(payGroup.getName());
            //发送企微群消息
            if (ObjectUtil.isNotEmpty(payGroup) && StrUtil.isNotEmpty(payGroup.getBotKey()) && ObjectUtil.isNotEmpty(studentInfo) && StrUtil.isNotEmpty(studentInfo.getId())) {
                SendQWmsgUtil.sendMsg(studentInfo, payGroup.getBotKey());
            }
        }
        return dispatchInfoMapper.insert(dispatchInfo);
    }

    /**
     * 修改派单记录
     *
     * @param dispatchInfo 派单记录
     * @return 结果
     */
    @Override
    public int updateEntity(DispatchInfo dispatchInfo) {
        dispatchInfo.setUpdateTime(DateUtil.date());
        return dispatchInfoMapper.updateById(dispatchInfo);
    }

    /**
     * 批量删除派单记录
     *
     * @param ids 需要删除的派单记录主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        return dispatchInfoMapper.deleteDispatchInfoByIds(ids);
    }

    /**
     * 删除派单记录信息
     *
     * @param id 派单记录主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return dispatchInfoMapper.deleteDispatchInfoById(id);
    }
}
